package com.zhsm.fuxi.mvp.ui.activitys

import android.content.Intent
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import com.hankkin.reading.base.TakePhotoMvpActivity
import com.hankkin.reading.control.UserControl
import com.hankkin.reading.event.EventMap
import com.zhsm.paipaiout.baselibrary.utils.RxBusTools
import com.zhsm.paipaiout.baselibrary.utils.ToastUtils
import com.zhsm.fuxi.R
import com.zhsm.fuxi.app.Constant
import com.zhsm.fuxi.bean.AttInfoBean
import com.zhsm.fuxi.bean.UserBean
import com.zhsm.fuxi.mvp.contract.AttContract
import com.zhsm.fuxi.mvp.presenter.AttPresenter
import com.zhsm.fuxi.mvp.ui.dialog.HintDialog
import com.zhsm.fuxi.mvp.ui.dialog.ChosePhotoWayDialog
import com.zhsm.fuxi.utils.CommonUtils
import com.zhsm.fuxi.utils.GlideUtils
import com.zhsm.paipaiout.baselibrary.widget.view.MyTextWatcher
import kotlinx.android.synthetic.main.activity_att.*
import kotlinx.android.synthetic.main.layout_head_bar.view.*
import org.devio.takephoto.model.TResult
import org.jetbrains.anko.imageResource
import org.jetbrains.anko.sdk25.coroutines.onClick

/**
 * Created by GuZhC on 2018/10/19.
 * describe:
 */
class AttActivity : TakePhotoMvpActivity<AttPresenter>(), AttContract.IView {
    var isfirst = true
    val mChosePhotoWayDialog: ChosePhotoWayDialog by lazy {
        ChosePhotoWayDialog(this)
    }
    val mAttHintDialog:  HintDialog by lazy {
        HintDialog(this)
    }
    val IMAGE_1 = 0
    val IMAGE_2 = 1
    val IMAGE_3 = 2
    val IMAGE_4 = 3
    //临时保存当前设置图片的imageview
    var nowImage = IMAGE_1
    //临时保存当前设置图片的imageviewPath
    var nowImagePath = ""
    val ET_ID_NAME = 4
    val ET_ID_NUM = 5
    val ET_LICENSE = 6

    //对应顺序 4张照片 3个输入框
    var inputIsOk = arrayListOf<Boolean>(false, false, false, false, false, false, false)
    //对应顺序 4张照片七牛云key
    var imageKey = arrayListOf<String>("", "", "", "")

    override fun getLayoutId(): Int {
        return R.layout.activity_att
    }

    override fun registerPresenter() = AttPresenter::class.java
    override fun isHasBus(): Boolean {
        return true
    }

    override fun initView() {
        setMiuiStatusBar()
        headBar.tvTitle.text = "实名认证"
        setClick()
        if (isfirst && UserControl.getCurrentUser()?.auth == Constant.AttState.ATTFAIL) {
            showLoding()
            getPresenter().getAttInfo()
            isfirst = false
        }
    }

    private fun setClick() {
        mChosePhotoWayDialog.setOnClickTakePhoto(object : ChosePhotoWayDialog.onClickTakePhoto {
            override fun takePic() {
                takePicture()
            }

            override fun chosePic() {
                chosePicture(1)
            }
        })
        headBar.imgLift.onClick { finish() }
        imgIdCardU.onClick {
            nowImage = IMAGE_1
            mChosePhotoWayDialog.show()
        }
        imgIdCardB.onClick {
            nowImage = IMAGE_2
            mChosePhotoWayDialog.show()
        }
        imgLicenseU.onClick {
            nowImage = IMAGE_3
            mChosePhotoWayDialog.show()
        }
        imgLicenseB.onClick {
            nowImage = IMAGE_4
            mChosePhotoWayDialog.show()
        }
        AttCommit.onClick {
            imageKey.forEachIndexed { index, s ->
                if (s.isNullOrBlank()) {
                    ToastUtils.makeText("请重新上传第${index + 1}张图片")
                    return@onClick
                }
            }
            showLoding()
            val map = HashMap<String, Any>()
            map["customerId"] = UserControl.getId()
            map["name"] = inputIdName.text.toString().trim()
            map["idCard"] = inputIdNum.text.toString().trim()
            map["idFront"] = imageKey[0]
            map["idBack"] = imageKey[1]
            map["license"] = inputLicenseNum.text.toString().trim()
            map["licFront"] = imageKey[2]
            map["licBack"] = imageKey[3]
            getPresenter().upAttInfo(map)
        }
        setEtChange(inputIdName, inputIdNameOk, inputIdNameLl, ET_ID_NAME)
        setEtChange(inputIdNum, inputIdNumOk, inputIdNumLl, ET_ID_NUM)
        setEtChange(inputLicenseNum, inputLicenseNumOk, inputLicenseNumLl, ET_LICENSE)
    }

    override fun setAttInfo(info: AttInfoBean?) {
        hideLoding()
        info?.run {
            inputIdName.setText(name)
            inputIdNum.setText(idCard)
            inputLicenseNum.setText(license)
            GlideUtils.loadImage(this@AttActivity, domain + idFront, imgIdCardU)
            GlideUtils.loadImage(this@AttActivity, domain + idBack, imgIdCardB)
            GlideUtils.loadImage(this@AttActivity, domain + licFront, imgLicenseU)
            GlideUtils.loadImage(this@AttActivity, domain + licBack, imgLicenseB)
            inputIsOk.forEachIndexed { index, b ->
                inputIsOk[index] = true
            }
            imageKey = arrayListOf(idFront!!, this.idBack!!, this.licFront!!, this.licBack!!)
            btnIsClick()
        }

    }
    override fun takeSuccess(result: TResult?) {
        result?.let {
            showLoding()
            nowImagePath = result.image.compressPath
            getPresenter().upPicToQiniu(it.image.compressPath)
        }
    }

    override fun upQiniuSucess(key: String) {
        hideLoding()
        lodeImage(key)
    }

    override fun upAttInfoSucess(user: UserBean?) {
        hideLoding()
        user?.let {
            UserControl.setCurrentUser(user)
            RxBusTools.getDefault().post(EventMap.UpUserInfoEvent())
        }
        startActivity(Intent(this, AttIngActivity::class.java))
        finish()
    }

    private fun lodeImage(key: String) {
        when (nowImage) {
            IMAGE_1 -> {
                imageKey[0] = key
                inputIsOk[0] = true
                GlideUtils.loadImage(this, nowImagePath, imgIdCardU)
            }
            IMAGE_2 -> {
                imageKey[1] = key
                inputIsOk[1] = true
                GlideUtils.loadImage(this, nowImagePath, imgIdCardB)
            }
            IMAGE_3 -> {
                imageKey[2] = key
                inputIsOk[2] = true
                GlideUtils.loadImage(this, nowImagePath, imgLicenseU)
            }
            IMAGE_4 -> {
                imageKey[3] = key
                inputIsOk[3] = true
                GlideUtils.loadImage(this, nowImagePath, imgLicenseB)
            }
        }
        btnIsClick()
    }

    private fun setEtChange(et: EditText, img: ImageView, bg: LinearLayout, w: Int) {
        et.addTextChangedListener(object : MyTextWatcher() {
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (!s.isNullOrEmpty()) {
                    bg.background = resources.getDrawable(R.drawable.bg_att_input)
                    if (w == ET_ID_NAME) {
                        img.imageResource =R.mipmap.write_right
                        img.visibility = View.VISIBLE
                        inputIsOk[4] = true
                    } else {
                        img.visibility = View.VISIBLE
                        if (CommonUtils.checkIDVardNum(s.toString().trim())) {
                            img.imageResource =R.mipmap.write_right
                            if (w == ET_ID_NUM) inputIsOk[5] = true
                            if (w == ET_LICENSE) inputIsOk[6] = true
                        } else {
                            img.imageResource =R.mipmap.att_input_no
                            if (w == ET_ID_NUM) inputIsOk[5] = false
                            if (w == ET_LICENSE) inputIsOk[6] = false
                        }
                    }
                } else {
                    bg.background = resources.getDrawable(R.drawable.bg_login_input)
                    img.visibility = View.GONE
                    if (w == ET_ID_NAME) inputIsOk[4] = false
                    if (w == ET_ID_NUM) inputIsOk[5] = false
                    if (w == ET_LICENSE) inputIsOk[6] = false
                }
                btnIsClick()
            }
        })
    }

    private fun btnIsClick() {
        inputIsOk.forEach {
            if (!it) {
                AttCommit.isEnabled = false
                return@btnIsClick
            }
            AttCommit.isEnabled = true
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mChosePhotoWayDialog.setOnClickTakePhoto(null)
    }

    override fun onBackPressed() {
        mAttHintDialog.setOnClickAndRes("现在退出将丢失信息",R.drawable.att_out_hint,true,"确定",
        object :HintDialog.onClickBtn{
            override fun cancelBtn() {
                mAttHintDialog.dismiss()
            }

            override fun sureBtn() {
               finish()
            }
        })
        mAttHintDialog.show()
    }
}